<script setup lang="ts">
import { ref, computed } from 'vue'
import { i18n } from 'boot/i18n'

const tc = i18n.global.tc

// 资源类型
const resourceTypes = [
  { value: '50', label: '50方会议室' },
  { value: '100', label: '100方会议室' },
  { value: '300', label: '300方会议室' },
  { value: '500', label: '500方会议室' }
]

// 模拟分组数据
const groups = ref([
  {
    id: 1,
    name: '技术部',
    description: '技术研发团队',
    userCount: 42,
    resources: ['50', '100', '300']
  },
  {
    id: 2,
    name: '市场部',
    description: '市场营销团队',
    userCount: 28,
    resources: ['50', '100']
  },
  {
    id: 3,
    name: '财务部',
    description: '财务管理团队',
    userCount: 15,
    resources: ['50']
  },
  {
    id: 4,
    name: '人事部',
    description: '人力资源团队',
    userCount: 18,
    resources: ['50', '100']
  },
  {
    id: 5,
    name: '管理层',
    description: '公司高层管理人员',
    userCount: 8,
    resources: ['50', '100', '300', '500']
  }
])

// 模拟用户数据
const users = ref([
  { id: 1, name: '张三', email: 'zhangsan@example.com', department: '技术部', groupId: 1 },
  { id: 2, name: '李四', email: 'lisi@example.com', department: '市场部', groupId: 2 },
  { id: 3, name: '王五', email: 'wangwu@example.com', department: '技术部', groupId: 1 },
  { id: 4, name: '赵六', email: 'zhaoliu@example.com', department: '财务部', groupId: 3 },
  { id: 5, name: '钱七', email: 'qianqi@example.com', department: '人事部', groupId: 4 },
  { id: 6, name: '孙八', email: 'sunba@example.com', department: '技术部', groupId: 1 },
  { id: 7, name: '周九', email: 'zhoujiu@example.com', department: '市场部', groupId: 2 },
  { id: 8, name: '吴十', email: 'wushi@example.com', department: '管理层', groupId: 5 }
])

// 当前编辑的分组
const editedGroup = ref(null)
const isNewGroup = ref(false)

// 分组编辑对话框
const groupDialog = ref(false)

// 成员管理对话框
const membersDialog = ref(false)
const selectedGroupForMembers = ref(null)
const availableUsers = ref([])
const selectedUsers = ref([])
const searchQuery = ref('')

// 权限管理对话框
const permissionsDialog = ref(false)
const selectedGroupForPermissions = ref(null)

// 删除确认对话框
const deleteConfirmDialog = ref(false)
const groupToDelete = ref(null)

// 编辑分组
const editGroup = (group) => {
  editedGroup.value = JSON.parse(JSON.stringify(group)) // 深拷贝避免直接修改原数据
  isNewGroup.value = false
  groupDialog.value = true
}

// 创建新分组
const createGroup = () => {
  editedGroup.value = {
    id: Math.max(...groups.value.map(g => g.id)) + 1,
    name: '',
    description: '',
    userCount: 0,
    resources: []
  }
  isNewGroup.value = true
  groupDialog.value = true
}

// 保存分组
const saveGroup = () => {
  if (!editedGroup.value) return

  if (isNewGroup.value) {
    // 添加新分组
    groups.value.push(editedGroup.value)
  } else {
    // 更新现有分组
    const index = groups.value.findIndex(g => g.id === editedGroup.value.id)
    if (index !== -1) {
      groups.value[index] = editedGroup.value
    }
  }

  groupDialog.value = false
  editedGroup.value = null
}

// 管理成员
const manageMembers = (group) => {
  selectedGroupForMembers.value = group

  // 获取当前分组成员和可添加的成员
  selectedUsers.value = users.value.filter(u => u.groupId === group.id)
  availableUsers.value = users.value.filter(u => u.groupId !== group.id)

  membersDialog.value = true
}

// 添加成员到分组
const addUserToGroup = (user) => {
  if (!selectedGroupForMembers.value) return

  // 修改用户的分组ID
  const userIndex = users.value.findIndex(u => u.id === user.id)
  if (userIndex !== -1) {
    users.value[userIndex].groupId = selectedGroupForMembers.value.id

    // 更新分组用户计数
    const groupIndex = groups.value.findIndex(g => g.id === selectedGroupForMembers.value.id)
    if (groupIndex !== -1) {
      groups.value[groupIndex].userCount++
    }

    // 更新显示的用户列表
    selectedUsers.value.push(user)
    availableUsers.value = availableUsers.value.filter(u => u.id !== user.id)
  }
}

// 从分组中移除成员
const removeUserFromGroup = (user) => {
  if (!selectedGroupForMembers.value) return

  // 修改用户的分组ID（设为null表示未分组）
  const userIndex = users.value.findIndex(u => u.id === user.id)
  if (userIndex !== -1) {
    users.value[userIndex].groupId = null

    // 更新分组用户计数
    const groupIndex = groups.value.findIndex(g => g.id === selectedGroupForMembers.value.id)
    if (groupIndex !== -1) {
      groups.value[groupIndex].userCount--
    }

    // 更新显示的用户列表
    selectedUsers.value = selectedUsers.value.filter(u => u.id !== user.id)
    availableUsers.value.push(user)
  }
}

// 管理权限
const managePermissions = (group) => {
  selectedGroupForPermissions.value = JSON.parse(JSON.stringify(group))
  permissionsDialog.value = true
}

// 保存权限
const savePermissions = () => {
  if (!selectedGroupForPermissions.value) return

  const index = groups.value.findIndex(g => g.id === selectedGroupForPermissions.value.id)
  if (index !== -1) {
    groups.value[index].resources = selectedGroupForPermissions.value.resources
  }

  permissionsDialog.value = false
}

// 弹出删除确认
const confirmDeleteGroup = (group) => {
  groupToDelete.value = group
  deleteConfirmDialog.value = true
}

// 删除分组
const deleteGroup = () => {
  if (!groupToDelete.value) return

  // 先将分组的用户设为未分组
  users.value.forEach(user => {
    if (user.groupId === groupToDelete.value.id) {
      user.groupId = null
    }
  })

  // 然后删除分组
  const index = groups.value.findIndex(g => g.id === groupToDelete.value.id)
  if (index !== -1) {
    groups.value.splice(index, 1)
  }

  deleteConfirmDialog.value = false
  groupToDelete.value = null
}

// 资源是否已分配
const hasResource = (group, resourceValue) => {
  return group.resources.includes(resourceValue)
}

// 切换资源分配
const toggleResource = (resourceValue) => {
  if (!selectedGroupForPermissions.value) return

  const index = selectedGroupForPermissions.value.resources.indexOf(resourceValue)
  if (index !== -1) {
    selectedGroupForPermissions.value.resources.splice(index, 1)
  } else {
    selectedGroupForPermissions.value.resources.push(resourceValue)
  }
}

// 格式化资源显示
const formatResources = (resources) => {
  return resources.map(r => {
    const resource = resourceTypes.find(rt => rt.value === r)
    return resource ? resource.label : r
  }).join(', ')
}

// 过滤可选用户
const filteredAvailableUsers = computed(() => {
  if (!searchQuery.value) return availableUsers.value

  const query = searchQuery.value.toLowerCase()
  return availableUsers.value.filter(user =>
    user.name.toLowerCase().includes(query) ||
    user.email.toLowerCase().includes(query) ||
    user.department.toLowerCase().includes(query)
  )
})
</script>

<template>
  <q-scroll-area style="height: calc(100vh - 50px)">
    <div class="q-pa-md">
      <h5 class="q-mt-none q-mb-md">{{ tc('分组管理') }}</h5>

      <!-- 工具栏 -->
      <div class="row q-mb-md items-center">
        <div class="col">
          <q-btn
            color="primary"
            :label="tc('创建分组')"
            icon="add"
            @click="createGroup"
          />
        </div>
      </div>

      <!-- 分组列表 -->
      <q-card>
        <q-card-section>
          <q-table
            :rows="groups"
            :columns="[
              { name: 'name', label: tc('分组名称'), field: 'name', align: 'left', sortable: true },
              { name: 'description', label: tc('描述'), field: 'description', align: 'left' },
              { name: 'userCount', label: tc('用户数'), field: 'userCount', align: 'center', sortable: true },
              {
                name: 'resources',
                label: tc('可用资源'),
                field: 'resources',
                align: 'left',
                format: val => formatResources(val)
              },
              { name: 'actions', label: tc('操作'), field: 'id', align: 'center' }
            ]"
            row-key="id"
            :pagination="{ rowsPerPage: 10 }"
          >
            <!-- 操作列 -->
            <template v-slot:body-cell-actions="props">
              <q-td :props="props">
                <q-btn
                  flat
                  round
                  color="primary"
                  icon="edit"
                  size="sm"
                  @click="editGroup(props.row)"
                >
                  <q-tooltip>{{ tc('编辑分组') }}</q-tooltip>
                </q-btn>

                <q-btn
                  flat
                  round
                  color="info"
                  icon="group"
                  size="sm"
                  @click="manageMembers(props.row)"
                >
                  <q-tooltip>{{ tc('管理成员') }}</q-tooltip>
                </q-btn>

                <q-btn
                  flat
                  round
                  color="warning"
                  icon="security"
                  size="sm"
                  @click="managePermissions(props.row)"
                >
                  <q-tooltip>{{ tc('资源权限') }}</q-tooltip>
                </q-btn>

                <q-btn
                  flat
                  round
                  color="negative"
                  icon="delete"
                  size="sm"
                  @click="confirmDeleteGroup(props.row)"
                >
                  <q-tooltip>{{ tc('删除分组') }}</q-tooltip>
                </q-btn>
              </q-td>
            </template>
          </q-table>
        </q-card-section>
      </q-card>

      <!-- 分组编辑对话框 -->
      <q-dialog v-model="groupDialog" persistent>
        <q-card style="min-width: 500px">
          <q-card-section class="row items-center">
            <div class="text-h6">{{ isNewGroup ? tc('创建分组') : tc('编辑分组') }}</div>
            <q-space />
            <q-btn icon="close" flat round dense v-close-popup />
          </q-card-section>

          <q-card-section v-if="editedGroup">
            <q-form>
              <div class="row q-col-gutter-md">
                <!-- 分组名称 -->
                <div class="col-12">
                  <q-input
                    v-model="editedGroup.name"
                    :label="tc('分组名称') + ' *'"
                    outlined
                    dense
                    required
                  />
                </div>

                <!-- 分组描述 -->
                <div class="col-12">
                  <q-input
                    v-model="editedGroup.description"
                    :label="tc('分组描述')"
                    outlined
                    dense
                    type="textarea"
                    autogrow
                  />
                </div>
              </div>
            </q-form>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat :label="tc('取消')" color="grey" v-close-popup />
            <q-btn :label="tc('保存')" color="primary" @click="saveGroup" />
          </q-card-actions>
        </q-card>
      </q-dialog>

      <!-- 成员管理对话框 -->
      <q-dialog v-model="membersDialog" persistent maximized>
        <q-card>
          <q-card-section class="row items-center">
            <div class="text-h6" v-if="selectedGroupForMembers">
              {{ tc('管理成员') }}: {{ selectedGroupForMembers.name }}
            </div>
            <q-space />
            <q-btn icon="close" flat round dense v-close-popup />
          </q-card-section>

          <q-card-section>
            <div class="row q-col-gutter-md">
              <!-- 可添加用户列表 -->
              <div class="col-12 col-md-6">
                <div class="text-h6 q-mb-md">{{ tc('可添加用户') }}</div>

                <q-input
                  v-model="searchQuery"
                  :label="tc('搜索用户')"
                  dense
                  outlined
                  class="q-mb-md"
                >
                  <template v-slot:append>
                    <q-icon name="search" />
                  </template>
                </q-input>

                <q-list bordered separator>
                  <q-item
                    v-for="user in filteredAvailableUsers"
                    :key="user.id"
                  >
                    <q-item-section>
                      <q-item-label>{{ user.name }}</q-item-label>
                      <q-item-label caption>{{ user.email }}</q-item-label>
                      <q-item-label caption>{{ user.department }}</q-item-label>
                    </q-item-section>

                    <q-item-section side>
                      <q-btn
                        flat
                        round
                        color="positive"
                        icon="add"
                        size="sm"
                        @click="addUserToGroup(user)"
                      >
                        <q-tooltip>{{ tc('添加到分组') }}</q-tooltip>
                      </q-btn>
                    </q-item-section>
                  </q-item>

                  <q-item v-if="filteredAvailableUsers.length === 0">
                    <q-item-section>
                      <q-item-label class="text-center text-grey">
                        {{ tc('没有可添加的用户') }}
                      </q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </div>

              <!-- 当前分组成员 -->
              <div class="col-12 col-md-6">
                <div class="text-h6 q-mb-md">{{ tc('当前分组成员') }}</div>

                <q-list bordered separator>
                  <q-item
                    v-for="user in selectedUsers"
                    :key="user.id"
                  >
                    <q-item-section>
                      <q-item-label>{{ user.name }}</q-item-label>
                      <q-item-label caption>{{ user.email }}</q-item-label>
                      <q-item-label caption>{{ user.department }}</q-item-label>
                    </q-item-section>

                    <q-item-section side>
                      <q-btn
                        flat
                        round
                        color="negative"
                        icon="remove"
                        size="sm"
                        @click="removeUserFromGroup(user)"
                      >
                        <q-tooltip>{{ tc('从分组移除') }}</q-tooltip>
                      </q-btn>
                    </q-item-section>
                  </q-item>

                  <q-item v-if="selectedUsers.length === 0">
                    <q-item-section>
                      <q-item-label class="text-center text-grey">
                        {{ tc('该分组没有成员') }}
                      </q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </div>
            </div>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn :label="tc('完成')" color="primary" v-close-popup />
          </q-card-actions>
        </q-card>
      </q-dialog>

      <!-- 权限管理对话框 -->
      <q-dialog v-model="permissionsDialog" persistent>
        <q-card style="min-width: 500px">
          <q-card-section class="row items-center">
            <div class="text-h6" v-if="selectedGroupForPermissions">
              {{ tc('资源权限') }}: {{ selectedGroupForPermissions.name }}
            </div>
            <q-space />
            <q-btn icon="close" flat round dense v-close-popup />
          </q-card-section>

          <q-card-section v-if="selectedGroupForPermissions">
            <div class="text-subtitle2 q-mb-sm">{{ tc('可预定资源') }}</div>

            <q-list bordered separator>
              <q-item v-for="resource in resourceTypes" :key="resource.value">
                <q-item-section avatar>
                  <q-checkbox
                    :model-value="hasResource(selectedGroupForPermissions, resource.value)"
                    @update:model-value="toggleResource(resource.value)"
                  />
                </q-item-section>

                <q-item-section>
                  <q-item-label>{{ resource.label }}</q-item-label>
                </q-item-section>
              </q-item>
            </q-list>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat :label="tc('取消')" color="grey" v-close-popup />
            <q-btn :label="tc('保存')" color="primary" @click="savePermissions" />
          </q-card-actions>
        </q-card>
      </q-dialog>

      <!-- 删除确认对话框 -->
      <q-dialog v-model="deleteConfirmDialog">
        <q-card>
          <q-card-section class="row items-center">
            <div class="text-h6">{{ tc('确认删除') }}</div>
          </q-card-section>

          <q-card-section v-if="groupToDelete">
            <p>{{ tc('您确定要删除分组') }} "{{ groupToDelete.name }}" {{ tc('吗？') }}</p>
            <p>{{ tc('该分组下的') }} {{ groupToDelete.userCount }} {{ tc('名用户将被解除分组关联。') }}</p>
            <p class="text-negative">{{ tc('此操作无法撤销。') }}</p>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat :label="tc('取消')" color="grey" v-close-popup />
            <q-btn :label="tc('删除')" color="negative" @click="deleteGroup" />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
  </q-scroll-area>
</template>
